package com.crm.system.service.impl.verifyPhone;

import com.beust.jcommander.internal.Lists;
import com.crm.common.helper.TimePeriod;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.verifyPhone.VerifyPhone;
import com.crm.model.qo.cluePoolManager.CustomerOnlineFollowQO;
import com.crm.model.qo.verifyPhone.VerifyPhoneQO;
import com.crm.model.qo.verifyPhone.VerifyPhoneReportQO;
import com.crm.model.vo.customerManager.CustomerContactVO;
import com.crm.model.vo.verifyPhone.VerifyPhoneReportVO;
import com.crm.model.vo.verifyPhone.VerifyPhoneVO;
import com.crm.service.verifyPhone.VerifyPhoneDbService;
import com.crm.system.service.callCenter.CallFormService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.user.UserAccountService;
import com.crm.system.service.verifyPhone.VerifyPhoneService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author renshaorong
 * @Date 2021/07/07 1:58 下午
 */
@Service
@Slf4j
public class VerifyPhoneServiceImpl implements VerifyPhoneService {

    @Autowired
    private VerifyPhoneDbService verifyPhoneDbService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ContactService contactService;

    @Autowired
    private UserAccountService accountService;

    @Autowired
    private CallFormService callFormService;


    /**
     * 获取分页列表
     * @param verifyPhoneQO
     * @return
     */
    @Override
    public DhPageInfo<VerifyPhoneVO> getVerifyPhoneList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, VerifyPhoneQO verifyPhoneQO){
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        verifyPhoneQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("v.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        if(!rs){//非超管
            verifyPhoneQO.setUserId(userAccount.getAccountId());
        }
        List<VerifyPhoneVO> verifyPhoneVOS = verifyPhoneDbService.selectAllVerifyPhoneList(verifyPhoneQO, order.toString());
        PageInfo<VerifyPhoneVO> pageInfo = new PageInfo<VerifyPhoneVO>(verifyPhoneVOS);
        return new DhPageInfo<VerifyPhoneVO>(pageInfo, verifyPhoneVOS);
    }

    /**
     * 拨打核实电话
     * @Author pym
     * @Date  2021/7/9 10:57
     * @param customerOnlineFollowQO 电话信息
     * @return {@link {java.lang.Boolean}}
     */
    @Override
    public String callVerifyPhone(CustomerOnlineFollowQO customerOnlineFollowQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        VerifyPhone verifyPhone = new VerifyPhone();
        verifyPhone.setVerifyId(CommonUtils.getGUID());//主键
        //verifyPhone.setContactName();联系人姓名
        verifyPhone.setContactPhone(customerOnlineFollowQO.getContactInformation());//联系电话
        int callDuration = customerOnlineFollowQO.getCallDuration();
        verifyPhone.setCallDuration(callDuration);//通话时长
        verifyPhone.setCallRecord(customerOnlineFollowQO.getCallRecord());//通话录音
        verifyPhone.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态---0: 正常; 1: 已删除
        verifyPhone.setCreateTm(new Date());//创建时间
        verifyPhone.setCreatePeopleId(accountId);//创建人ID
        verifyPhone.setUpdateTm(new Date());//更新时间
        verifyPhone.setUpdatePeopleId(accountId);//更新人ID
        //通话状态
        if (callDuration > 0) {
            verifyPhone.setCallStatus((short) 1);
        } else {
            verifyPhone.setCallStatus((short) 2);
        }
        verifyPhone.setMsgStatus((short) 1);//信息状态：1-有效，2-无效
        verifyPhone.setUserId(accountId);//用户ID
        verifyPhone.setCompanyId(userAccount.getCompanyId());//所属分公司ID
        //verifyPhone.setCustomerId();//关联客户ID
        if(verifyPhoneDbService.insertVerifyPhone(verifyPhone)){
            return verifyPhone.getVerifyId();
        }else{
            return null;
        }

    }

    /**
     * 修改
     * @param verifyPhone
     * @return
     */
    @Override
    public boolean updateVerifyPhoneInfo(VerifyPhone verifyPhone) {
        return verifyPhoneDbService.updateByPrimaryKeySelective(verifyPhone);
    }


    /**
     * 关联企业列表
     * @return
     */
    @Override
    public List<Customer> getCompCustomerList() {
        StringBuilder order = new StringBuilder();
        order.append("create_tm ").append(" desc");
        List<Customer> verifyPhoneVOS = customerService.getCompCustomerList(order.toString());
        return verifyPhoneVOS;
    }

    /**
     * 关联企业
     * @param verifyId
     * @param customerId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public boolean bindCustomer(String verifyId, String customerId, String contactName) {
        VerifyPhone verifyPhone = verifyPhoneDbService.selectVerifyPhoneById(verifyId);
        if(verifyPhone.getDeleteStatus().equals(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())))) return false;
        if(StringUtils.isNotEmpty(contactName)) verifyPhone.setContactName(contactName);

        //判断该联系人电话在该公司下是否存在
        if(contactService.checkExist(customerId,verifyPhone.getContactPhone())) return false;

        CustomerContactVO customerContactVO = new CustomerContactVO();
        customerContactVO.setContactInformation(verifyPhone.getContactPhone());
        customerContactVO.setContactType("单位电话");
        customerContactVO.setContactName(verifyPhone.getContactName());
        customerContactVO.setContactInformationType(1);
        customerContactVO.setCustomerId(customerId);
        customerContactVO.setContactNature("0");
        customerContactVO.setMergeState("0");
        //创建联系人及联系人大表
        String contactId = contactService.addContact(customerContactVO);
        verifyPhone.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        if (!StringUtils.isBlank(contactId) || !StringUtils.isBlank(customerContactVO.getContactId())) {  //有值
            //成功,核实电话表本条信息标识删除
            verifyPhone.setCustomerId(customerId);
        }
        return verifyPhoneDbService.updateByPrimaryKeySelective(verifyPhone);
    }



    /**
     * @Description: 电话核实报表
     * @Param: [reportQO]
     * @Return: java.util.List<com.crm.model.vo.verifyPhone.VerifyPhoneReportVO>
     * @Author: lixq-f
     * @Date: 2021/7/13
     **/
    @Override
    public List<VerifyPhoneReportVO> getVerifyPhoneReport(VerifyPhoneReportQO reportQO) {


        List<VerifyPhoneReportVO> resultList = Lists.newArrayList();
        if (null == reportQO.getDateUnit() && null == reportQO.getStartTm() && null == reportQO.getEndTm()){
            return resultList;
        }

        reportQO.setDateUnitStartTm(TimePeriod.getStartTime(reportQO.getDateUnit()));
        reportQO.setDateUnitEndTm(TimePeriod.getEndTime(reportQO.getDateUnit()));

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
/*
        List<UserAccountManagerVO> userAccounts = null;
        if(!CommonUtils.isAdmin(userAccount.getUserId())){
            reportQO.setCompanyId(userAccount.getCompanyId());
            userAccounts = accountService.getAbleAccountListByCompanyId(userAccount.getCompanyId());
        }else {
            userAccounts = accountService.getAllUsedAccountList();
        }

        if (CollectionUtils.isEmpty(userAccounts)){
            return resultList;
        }*/

        if(!CommonUtils.isAdmin(userAccount.getUserId())){
            reportQO.setCompanyId(userAccount.getCompanyId());
        }

        List<VerifyPhoneReportVO> le30List = verifyPhoneDbService.getLe30VerifyPhoneReport(reportQO);
        List<VerifyPhoneReportVO> ge30Lt60List = verifyPhoneDbService.getGe30Lt60VerifyPhoneReport(reportQO);
        List<VerifyPhoneReportVO> ge60Lt90List = verifyPhoneDbService.getGe60Lt90VerifyPhoneReport(reportQO);
        List<VerifyPhoneReportVO> ge90List = verifyPhoneDbService.getGe90VerifyPhoneReport(reportQO);

        /*if (CollectionUtils.isEmpty(le30List) && CollectionUtils.isEmpty(ge60Lt90List) && CollectionUtils.isEmpty(ge90List)){
            return resultList;
        }*/

        Map<String, VerifyPhoneReportVO> le30Map = null;
        if (CollectionUtils.isEmpty(le30List)){
            le30List = Lists.newArrayList();
        }else {
            le30Map = le30List
                    .stream()
                    .collect(Collectors.toMap(VerifyPhoneReportVO::getAccountId, VerifyPhoneReportVO -> VerifyPhoneReportVO));
        }

        Map<String, VerifyPhoneReportVO> ge30Lt60Map = null;
        if (!CollectionUtils.isEmpty(ge30Lt60List)){
            le30List.addAll(ge30Lt60List);
            ge30Lt60Map = ge30Lt60List
                    .stream()
                    .collect(Collectors.toMap(VerifyPhoneReportVO::getAccountId, VerifyPhoneReportVO -> VerifyPhoneReportVO));
        }

        Map<String, VerifyPhoneReportVO> ge60Lt90Map = null;
        if (!CollectionUtils.isEmpty(ge60Lt90List)){
            le30List.addAll(ge60Lt90List);
            ge60Lt90Map = ge60Lt90List
                    .stream()
                    .collect(Collectors.toMap(VerifyPhoneReportVO::getAccountId, VerifyPhoneReportVO -> VerifyPhoneReportVO));
        }

        Map<String, VerifyPhoneReportVO> ge90Map = null;
        if (!CollectionUtils.isEmpty(ge90List)){
            le30List.addAll(ge90List);
            ge90Map = ge90List
                    .stream()
                    .collect(Collectors.toMap(VerifyPhoneReportVO::getAccountId, VerifyPhoneReportVO -> VerifyPhoneReportVO));
        }


        Map<String, Long> map = le30List
                .stream()
                .collect(Collectors.groupingBy(VerifyPhoneReportVO::getAccountId, Collectors.counting()));


//        ArrayList<VerifyPhoneReportVO> collect = le30List.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(VerifyPhoneReportVO::getUserName))), ArrayList::new));

        VerifyPhoneReportVO vo = null;
        for (String accountId : map.keySet()) {
            vo = new VerifyPhoneReportVO();
            vo.setAccountId(accountId);

            if (Objects.nonNull(le30Map)){
                VerifyPhoneReportVO le30VO = le30Map.get(accountId);
                if (Objects.nonNull(le30VO)){
                    vo.setLe30SecondCount(le30VO.getLe30SecondCount());
                    vo.setUserName(le30VO.getUserName());
                }else {
                    vo.setLe30SecondCount(0);
                }
            }else {
                vo.setLe30SecondCount(0);
            }

            if (Objects.nonNull(ge30Lt60Map)){
                VerifyPhoneReportVO ge30Lt60VO = ge30Lt60Map.get(accountId);
                if (Objects.nonNull(ge30Lt60VO)){
                    vo.setGe30lt60SecondCount(ge30Lt60VO.getGe30lt60SecondCount());
                    vo.setUserName(ge30Lt60VO.getUserName());
                }else {
                    vo.setGe30lt60SecondCount(0);
                }
            }else {
                vo.setGe30lt60SecondCount(0);
            }

            if (Objects.nonNull(ge60Lt90Map)){
                VerifyPhoneReportVO ge60Lt90VO = ge60Lt90Map.get(accountId);
                if (Objects.nonNull(ge60Lt90VO)){
                    vo.setGe60lt90SecondCount(ge60Lt90VO.getGe60lt90SecondCount());
                    vo.setUserName(ge60Lt90VO.getUserName());
                }else {
                    vo.setGe60lt90SecondCount(0);
                }
            }else {
                vo.setGe60lt90SecondCount(0);
            }

            if (Objects.nonNull(ge90Map)){
                VerifyPhoneReportVO ge90VO = ge90Map.get(accountId);
                if (Objects.nonNull(ge90VO)){
                    vo.setGe90SecondCount(ge90VO.getGe90SecondCount());
                    vo.setUserName(ge90VO.getUserName());
                }else {
                    vo.setGe90SecondCount(0);
                }
            }else {
                vo.setGe90SecondCount(0);
            }

            resultList.add(vo);
        }

//        Map<String, VerifyPhoneReportVO> finalMap = resultList
//                .stream()
//                .collect(Collectors.toMap(VerifyPhoneReportVO::getAccountId, VerifyPhoneReportVO -> VerifyPhoneReportVO));

//        List<VerifyPhoneReportVO> finalList = Lists.newArrayList();
//        VerifyPhoneReportVO finalVO = null;
        /*for (UserAccountManagerVO account : userAccounts) {
            VerifyPhoneReportVO phoneReportVO = finalMap.get(account.getAccountId());
            if (Objects.isNull(phoneReportVO)){
                finalVO = new VerifyPhoneReportVO();
                finalVO.setAccountId(account.getAccountId());
                finalVO.setUserName(account.getUserName());
                finalVO.setGe60lt90SecondCount(0);
                finalVO.setLe30SecondCount(0);
                finalVO.setGe90SecondCount(0);
                finalList.add(finalVO);
            }else {
                finalList.add(phoneReportVO);
            }
        }*/

//        return finalList;
        return resultList;
    }


    /**
     * 获取通话录音
     * @param verifyId
     * @return
     */
    @Override
    public String getCallRecord(String verifyId){
        VerifyPhone verifyPhone = verifyPhoneDbService.selectVerifyPhoneById(verifyId);
        return callFormService.getSecretUrl(verifyPhone.getCallRecord());
    }

    /**
     * 核实电话 管理端表格数据，返回分公司下个人 <30 <60 <90 >90 总时长数据
     * @param dateUnit
     * @return
     */
    @Override
    public DhPageInfo<VerifyPhoneReportVO> getDurationByCompanyId(Integer pageIndex, Integer pageSize, Integer dateUnit){
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<VerifyPhoneReportVO> durationByCompanyId = verifyPhoneDbService.getDurationByCompanyId(dateUnit, userAccount.getCompanyId());
        PageInfo<VerifyPhoneReportVO> pageInfo = new PageInfo<VerifyPhoneReportVO>(durationByCompanyId);
        return new DhPageInfo<VerifyPhoneReportVO>(pageInfo, durationByCompanyId);
    }

    /**
     * 核实电话 超管端表格数据，返回各分公司下 <30 <60 <90 >90 总时长数据 平均数
     * @param dateUnit
     * @return
     */
    @Override
    public List<Map<String,Object>> getAllDurationGroupByCompanyId(Integer dateUnit){
        return verifyPhoneDbService.getAllDurationGroupByCompanyId(dateUnit);
    }

}
